package com.shangxia.dog.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shangxia.dog.commom.pojo.ResultVO;
import com.shangxia.dog.config.security.JwtTokenUtil;
import com.shangxia.dog.mapper.AdminMapper;
import com.shangxia.dog.pojo.dao.Admin;
import com.shangxia.dog.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author shangxia
 * @since 2022-01-16
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Override
    public ResultVO<String> login(String username, String password, HttpServletRequest request) {
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (null == userDetails || !passwordEncoder.matches(password, userDetails.getPassword())) {
            return ResultVO.error("用户或密码错误");
        }
        if (!userDetails.isEnabled()) {
            return ResultVO.error("账号被禁用，请联系管理员");
        }
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        map.put("tokenHead", tokenHead);
        return ResultVO.success("登录成功", map);
    }
}
